package com.fitz.serializer;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author fitz 2020-5-6 19:52
 */

public class HessianSerializer implements Serializer {

    @Override
    public byte getSerializerType() {
        return SerializerType.HESSIAN;
    }

    @Override
    public <T> byte[] serialize(T t) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output ho = new Hessian2Output(os);
        try {
            ho.writeObject(t);
            ho.flush();
            byte[] result = os.toByteArray();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                ho.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public <T> T deSerialize(Class<T> clazz, byte[] bytes) {
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Hessian2Input hi = new Hessian2Input(is);
        Object result = null;
        try {
            result = hi.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                hi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return (T) result;
    }
}
